import React,{Component,PureComponent} from "react";
import {
  View,
  Text,
  ScrollView,
  StyleSheet,
  Image,
  TouchableWithoutFeedback,
  FlatList,
  Modal,
  ActivityIndicator,
} from "react-native";
import {width,isIphoneX} from "../../util/apdater_util";
import {Card} from 'react-native-shadow-cards';
import ScrollableTabView, { ScrollableTabBar,DefaultTabBar} from 'react-native-scrollable-tab-view';
import PropTypes from "prop-types";
import ImageViewer from 'react-native-image-zoom-viewer';
import CustomerHeader from "../../widget/customerHeader";
import JobContributeList from "./JobContributeList";
import JobCommentList from "./JobCommentList";
import  LinearGradient from 'react-native-linear-gradient';
import ChatInputBar from './ChatInputBar';
import NetUtil from '../../net/net_util'
import Loading from "../../widget/Loading";
import Toast from "../../widget/Toast";
import img_arr from "../../util/img_arr";

let _this=null;
class JobDetailTabBar extends Component{
  constructor(props) {
    super(props);
  }
  static propTypes = {
    tabLabelNames: PropTypes.array, // tabs
    goToPage: PropTypes.func, // 跳转到对应tab的方法
    tabs: PropTypes.array,
    activeTab: PropTypes.number,
    onPress:PropTypes.func
  }
  render() {
    const containerWidth = this.props.containerWidth;
    const numberOfTabs = this.props.tabs.length;
    const translateX = this.props.scrollValue.interpolate({
      inputRange: [0, 1],
      outputRange: [0, containerWidth / numberOfTabs],
    });
    return (
      <View style={[this.props.style,styles.tabs]}>
        {this.props.tabs.map((tab,i)=>{
          return <TouchableWithoutFeedback style={styles.tabBox} key={tab} onPress={()=>this.props.goToPage(i)}>
            <View style={styles.tabBox}>
              <Text style={[styles.tab,i === this.props.activeTab?{fontSize:14,color:'#222222'}:{}, this.props.textStyle]}>{this.props.tabLabelNames[i].label}</Text>
              {i===this.props.activeTab?<Image style={styles.lineBar}  source={require('../../img/line_bar.png')}></Image>:null}
            </View>
          </TouchableWithoutFeedback>
        })}
        <View style={styles.bottomLine}></View>
      </View>
    );
  }
}

class JobDetail extends PureComponent{
  constructor(props) {
    super(props);
    _this=this;
    this.jobContributeList=null;
    this.jobCommentList=null;
    this.state={
      canAction:false,
      isImageViewer:false,
      imageIndex:0,
      photos:[],
      jobId:'',
      currentIndex:0,
      workInfo:null,
      tabList:[
        {
          label:'投稿',
          index:1
        },{
          label:'评论',
          index:2
        }
      ],
      statusList:['征稿中','选稿中','公示中','已结束'],
    };
    this.tabView=null;
    this.chatInputBar=null;
  }

  componentDidMount() {
    _this=this;
    let jobId=this.props.route.params.jobId;
    this.state.jobId=jobId
    this.getWorkDetail(jobId)
  }

  _onBtnPress(){
    this.chatInputBar.openInputBar();
  }

  _onSendMsg(text){
    this.setState({
      chatMsg:text,
    });
    this.comment(text)
  }

  /*获取需求详情*/
  getWorkDetail(){
    NetUtil.get('work/job/detail',{jobId:this.state.jobId},(res)=>{
      this.chatInputBar.closeInputBar()
      if(res.code==200){
        this.setState({workInfo:res.data})
      }
    })
  }

  /*点赞*/
  like(){
    Loading.show()
    NetUtil.postFrom('work/job/like',{id:this.state.jobId},(res)=>{
      Loading.hide()
      if(res.code==200){
        this.getWorkDetail(this.state.jobId)
      }
      else {
        Toast.add(res.msg)
      }
    })
  }

  /*发布评论*/
  comment(text){
    let params={
      content:text,
      isReply:0,
      jobId:this.state.jobId,
    }
    Loading.show()
    NetUtil.postFrom('work/job/comment/create',params,(res)=>{
      Loading.hide()
      this.chatInputBar.closeInputBar()
      if(res.code==200){
        Toast.add('发布成功')
        _this.jobContributeList.clearData()
        if(_this.jobCommentList&&_this.jobCommentList.reload){
          _this.jobCommentList.reload()
        }
        if(_this.tabView)_this.tabView.goToPage(1)
      }
      else {
        Toast.add(res.msg)
      }
    })
  }


  /*投稿*/
  goToContribute(){
    this.props.navigation.navigate('ContributeWork',{jobId:this.state.jobId,callback:(()=>{
      this.jobContributeList.reload()
    })})
  }
  /*预览大图*/
  imagePreviewViewer(index){
    let photos=this.state.workInfo.images;
    let imageList=photos.map((img,idex)=>{
      return {url:img}
    })
    this.setState(
      {imageIndex:index,
      isImageViewer:true,
      photos:imageList})
  }

  /*切换的时候*/
  onChangeTab(obj){
    let index=obj.i
    _this.setState({currentIndex:index})
    if(index==0){
      _this.jobContributeList.reload()
      _this.jobCommentList.clearData()
    }
    else {
      _this.jobContributeList.clearData()
      _this.jobCommentList.reload()
    }
  }
  selectTabChange(i){
    _this.setState({currentIndex:i})
    if(index==0){
      _this.jobContributeList.reload()
      _this.jobCommentList.clearData()
    }
    else {
      _this.jobContributeList.clearData()
      _this.jobCommentList.reload()
    }
    if(_this.tabView)_this.tabView.goToPage(i)
  }

  loadMore(){
    if(this.state.currentIndex==0){
      _this.jobContributeList._endReached()
    }
    else {
      _this.jobCommentList._endReached()
    }
  }

   isReachedEnd = ({layoutMeasurement, contentOffset, contentSize}) => {
    const paddingToBottom = 10;

    return layoutMeasurement.height + contentOffset.y >= contentSize.height - paddingToBottom;
  };

  render() {
    return (<View style={{height: '100%',backgroundColor:'#fff'}}>
      <CustomerHeader leftOnPress={()=>{this.props.navigation.pop()}} title={'需求详情'}></CustomerHeader>
      {this.state.workInfo?(
        <ScrollView scrollEnabled={true}
                    style={{height: '100%'}}
                    onScroll={({nativeEvent}) => {
                      if (this.isReachedEnd(nativeEvent)) {
                        this.loadMore()
                      }
                    }}
                    showsVerticalScrollIndicator={false}>
          <Card style={styles.card} elevation={3} opacity={0.2} cornerRadius={5}>
            <View style={styles.workInfo}>
              <View style={styles.titleBox}>
                <View style={[styles.flexBox]}>
                  {this.state.workInfo.hot==1?<Image style={styles.hot} source={require('../../img/hot_work_icon.png')}></Image>:null}
                  <Text style={styles.title}>{this.state.workInfo.title}</Text>
                </View>
                <Text style={styles.score}>{this.state.workInfo.points}积分</Text>
              </View>
              <View style={styles.tags}>
                <Text style={styles.tag}>{this.state.workInfo.skillName}</Text>
                <Text style={styles.tag}>{this.state.workInfo.industryName}</Text>
              </View>
              <View style={styles.line}></View>
              <View style={styles.itemBox}>
                <View style={styles.item}>
                  <Text style={styles.itemTitle}>截止时间</Text>
                  <Text style={styles.itemContent}>{this.state.workInfo.deadlineTime}</Text>
                </View>
                <View style={styles.item}>
                  <Text style={styles.itemTitle}>参与人数</Text>
                  <Text style={styles.itemContent}>{this.state.workInfo.joinNum}</Text>
                </View>
                <View style={styles.item}>
                  <Text style={styles.itemTitle}>发布人</Text>
                  <View style={{flexDirection:'row',justifyContent:'center',alignItems:'center',marginTop:8}}>
                    <Image style={{width:15,height:15,borderRadius:7.5,marginRight:4}} source={{uri:this.state.workInfo.avatar}}></Image>
                    <Text style={{color:'#000000',fontSize:11}}>{this.state.workInfo.nickName}</Text>
                  </View>
                </View>
              </View>
              <View style={styles.line}></View>
              <Text style={styles.des}>{this.state.workInfo.content}</Text>
              <ScrollView style={{marginTop:10}} scrollEnabled={true} horizontal={true} showsHorizontalScrollIndicator={false}>
                {this.state.workInfo.images.map((item,index)=>{
                  return <TouchableWithoutFeedback onPress={this.imagePreviewViewer.bind(this,index)} key={'img'+index}>
                    <Image style={styles.img} source={{uri:item}}></Image>
                  </TouchableWithoutFeedback>
                })}
              </ScrollView>
            </View>
          </Card>
          <View style={{marginTop:18,paddingBottom:25}}>
            <View style={styles.progressTitleBox}>
              <Image style={styles.proTitleIcon} source={require('../../img/progress_icon.png')}></Image>
              <Text style={styles.proTitle}>任务进度</Text>
            </View>
            <View style={styles.progressBox}>
              {this.state.statusList.map((status,index)=>{
                return (
                  <View style={styles.progressBoxItem} key={'status'+index}>
                    {index>0?<View style={styles.leftLine}></View>:null}
                    <View style={[styles.dot,{backgroundColor:this.state.workInfo.status>=index+1?'#E39354':'#DCDCDC'}]}></View>
                    <Text style={[styles.progressItemTitle,{color:this.state.workInfo.status>=index+1?'#E39354':'#DCDCDC'}]}>{status}</Text>
                    {index<this.state.statusList.length-1?<View style={styles.rightLine}></View>:null}
                  </View>
                )
              })}
            </View>
          </View>
          <View style={{backgroundColor:'#F6F6F6',height:10}}></View>
          <View style={{height: '100%'}}>
            <ScrollableTabView style={{height:'100%'}} initialPage={0} ref={(tabView) => { this.tabView = tabView; }} prerenderingsiblingsNumber={1} scrollWithoutAnimation={false} onChangeTab={this.onChangeTab} onScroll={
              (position) => {

              }
            } locked={false} renderTabBar={()=><JobDetailTabBar tabLabelNames={this.state.tabList} onPress={this.selectTabChange}/>}>
              <View tabLabel="Tab1" style={{height: '100%'}}>
                <JobContributeList ref={(ref)=>this.jobContributeList=ref}
                                   isCanAction={this.state.canAction}
                                   callback={this.getWorkDetail.bind(this)}
                                   jobId={this.state.jobId}
                                   data={this.state.workInfo}>
                </JobContributeList>
              </View>
              <View tabLabel='Tab2' style={{height: '100%'}}>
                <JobCommentList ref={(ref)=>this.jobCommentList=ref} isCanAction={this.state.canAction} jobId={this.state.jobId}></JobCommentList>
              </View>
            </ScrollableTabView>
          </View>
        </ScrollView>
      ):(<View style={styles.loading}>
        <ActivityIndicator color="#f8da85"/>
      </View>)}
      {(this.state.workInfo&&!this.state.workInfo.isSelf)?(
        <View style={[styles.toolBar,{height:isIphoneX()?83:50}]}>
          <TouchableWithoutFeedback onPress={this._onBtnPress.bind(this)}>
            <View style={styles.inputContainer}>
              <Text style={styles.inputTxt}>说点什么...</Text>
            </View>
          </TouchableWithoutFeedback>
          <View style={{marginLeft:30,marginTop:8}}>
            <Image style={{width:20,height:20}} source={require('../../img/share_black.png')}></Image>
            {(this.state.workInfo&&this.state.workInfo.shareNum>0)?(
              <View style={styles.num}><Text style={styles.numTitle}>{this.state.workInfo.shareNum}</Text></View>
            ):null}
          </View>
          <TouchableWithoutFeedback onPress={this.like.bind(this)}>
            <View style={{marginLeft:30,marginTop:8}}>
              <Image style={{width:20,height:20}} source={(this.state.workInfo&&this.state.workInfo.isLike==1)?img_arr.icon_favor_selected:img_arr.icon_favor_normal}></Image>
              {(this.state.workInfo&&this.state.workInfo.likeNum>0)?(
                <View style={styles.num}><Text style={styles.numTitle}>{this.state.workInfo.likeNum}</Text></View>
              ):null}
            </View>
          </TouchableWithoutFeedback>
          {(this.state.workInfo&&this.state.workInfo.status==1)?(
            <LinearGradient colors={['#e79c58','#f8da85']} style={styles.contributeBtn} start={{x:0,y:1}}>
              <Text style={styles.contributeBtnTitle} onPress={()=>{this.goToContribute()}}>我要投稿</Text>
            </LinearGradient>
          ):(
            <View style={styles.contributeBtn}>
              <Text style={styles.contributeBtnTitle}>截止投稿</Text>
            </View>
          )}
        </View>
      ):null}
      <ChatInputBar ref={s => this.chatInputBar = s} isVisible={true} onSend={(text) => this._onSendMsg(text)}></ChatInputBar>
      {this.state.isImageViewer?(
        <Modal transparent={true} visible={true} onRequestClose={()=> {
          this.setState({
            isImageViewer: false,
          });
        }}>
          <ImageViewer enableSwipeDown
                       enableImageZoom={true}
                       onClick={() => { // 图片单击事件
                         this.setState({
                           isImageViewer: false,
                         });
                       }}
                       imageUrls={this.state.photos}
                       onCancel={()=> {
                         this.setState({
                           isImageViewer: false,
                         });
                       }}
                       index={this.state.imageIndex}
                       saveToLocalByLongPress={false}/>
        </Modal>
      ):null}
      <Loading></Loading>
      <Toast></Toast>
    </View>)
  }
}

export default module=JobDetail

const styles=StyleSheet.create({
  bottomLine:{
    position:'absolute',
    height:1,
    backgroundColor:'#F6F6F6',
    left:0,
    right:0,
    bottom:0
  },
  card:{
    marginLeft: 12,
    width:width-24,
    marginVertical:8,
    paddingBottom:14
  },
  workInfo:{
    paddingLeft: 12,
    paddingRight:12,
    flex:1,
    marginTop:15
  },
  titleBox:{
    flexDirection:'row',
    justifyContent:'space-between',
    alignItems:'center'
  },
  flexBox:{
    flexDirection:'row',
    justifyContent:'flex-start',
  },
  hot:{
    width:16,
    height:16,
    marginRight:5
  },
  title:{
    color:'#0F0F0F',
    fontSize: 15,
    fontWeight:'500'
  },
  score:{
    color:'#E39354',
    fontSize:15,
    fontWeight: '500'
  },
  tags:{
    flexDirection:'row',
    marginTop: 8,
    justifyContent:'flex-start',
    flexWrap:'wrap',
    width:'100%',
  },
  tag:{
    backgroundColor:'#F6F6F6',
    color:'#3F3F3F',
    fontSize:11,
    height:19,
    lineHeight: 19,
    textAlign: 'center',
    paddingHorizontal:5,
    borderRadius:3,
    marginRight:4,
    marginBottom:5
  },
  des:{
    color:'#3F3F3F',
    fontSize:11,
    marginTop: 17
  },
  line:{
    height:1,
    backgroundColor: '#F6F6F6',
    marginTop:10
  },
  itemBox:{
    flexDirection:'row',
    justifyContent:'flex-start',
    alignItems: 'center',
    height:60,
    paddingTop:10
  },
  item:{
    flex:1,
    flexDirection:'column',
    justifyContent:'center',
    alignItems:'center'
  },
  itemTitle:{
    color:'#A5A5A5',
    fontSize:11
  },
  itemContent:{
    color:'#0F0F0F',
    fontSize:12,
    marginTop:9
  },
  img:{
    width:(width-70)/3.0,
    height:(width-64)/3.0,
    marginRight:10,
    borderRadius: 4
  },
  progressTitleBox:{
    flexDirection:'row',
    justifyContent:'flex-start',
    alignItems:'center',
    marginLeft: 15,
  },
  proTitleIcon:{
    width:12,
    height:12
  },
  proTitle:{
    color:'#343434',
    fontSize:11,
    marginLeft:7
  },
  progressBox:{
    flexDirection:'row',
    justifyContent:'flex-start',
    alignItems:'center',
    marginTop:20
  },
  progressBoxItem:{
    flex:1,
    position: 'relative',
    flexDirection:'column',
    justifyContent:'center',
    alignItems:'center'
  },
  dot:{
    width:9,
    height:9,
    borderRadius:4.5,
    zIndex:0,
  },
  rightLine:{
    position:'absolute',
    zIndex:-9999,
    height:1,
    right:0,
    top:4.5,
    left:'50%',
    backgroundColor:'#DCDCDC50',
  },
  leftLine:{
    position:'absolute',
    zIndex:-9999,
    height:1,
    left:0,
    top:4.5,
    right: '50%',
    backgroundColor:'#DCDCDC50',
  },
  progressItemTitle:{
    color:'#343434',
    fontSize:9,
    marginTop:9
  },

  /**tab**/
  tabs:{
    height:50,
    backgroundColor:'#fff',
    flexDirection:'row',
    justifyContent:'flex-start',
    alignItems:'center',
  },
  tabBox:{
    height:50,
    justifyContent: 'center',
    alignItems:'center'
  },
  tab:{
    color: '#666666',
    fontSize: 14,
    paddingLeft: 14,
    paddingRight:14
  },
  lineBar:{
    position:'absolute',
    width:20,
    height:3,
    top:40
  },
  /*工具条*/
  toolBar:{
    backgroundColor:'#fff',
    height:83,
    flexDirection:'row',
    justifyContent:'flex-start',
    paddingTop:8,
    borderTopStyle:'solid',
    borderTopWidth:1,
    borderTopColor:'#F8F8F8',
    paddingHorizontal: 15
  },

  contributeBtn:{
    width:90,
    height:34,
    textAlign: 'center',
    borderRadius:17,
    textAlignVertical:'center',
    backgroundColor:'#BFBFBF',
    marginLeft:26,
  },
  contributeBtnTitle:{
    color:'#fff',
    fontSize:14,
    flex:1,
    lineHeight:34,
    textAlign:'center',
    fontWeight:'500'
  },
  num:{
    position:'absolute',
    paddingHorizontal:5,
    height:12,
    right:-12,
    top:-6,
    borderRadius:6,
    backgroundColor:'red'
  },
  numTitle:{
    color:'#FFFFFF',
    fontSize:8,
    flex:1,
    lineHeight:11,
    textAlign:'center'
  },
  inputContainer:{
    backgroundColor:'#F6F7F9',
    height:34,
    borderRadius:17,
    flex:1,
    paddingLeft:15
  },
  inputTxt:{
    color:'#9E9FA1',
    fontSize:12,
    height:'100%',
    width:'100%',
    lineHeight:34,
  },
  flag:{
    width:42,
    height:42,
    position:'absolute',
    top:19,
    right:15
  },
  commentTitleBox:{
    flexDirection:'row',
    justifyContent:'space-between',
    alignItems:'center'
  },
  favorBox:{
    flexDirection:'row',
    justifyContent:'flex-end',
    alignItems:'center'
  },
  comment:{
    backgroundColor:'#F6F6F8',
    paddingHorizontal:10,
    paddingVertical: 12,
    marginTop:8,
    marginRight:15,
    borderRadius:2
  },
  name:{
    color:'#262626',
    fontSize:12,
    fontWeight:'500'
  },
  commentDes:{
    color:'#565656',
    fontSize:12
  },
  commentItem:{
    marginBottom: 10
  },
  replay:{
    color:'#3CA1FD',
    fontSize:11
  },
  replayTitle:{
    color:'#565656',
    fontSize:11,
    marginLeft:10,
    marginRight:10
  },
  loading:{
    flex:1,
    justifyContent:'center',
    alignItems:'center'
  }
})


